Scoring your trained model

In the cell below, please load your model into model. Also if you used an image size for your input images that isn't 224x224, you'll need to set image_size to the size you used. The scoring code assumes square input images.

For example, this is how I loaded in my checkpoint:

import torch
from torch import nn
import torch.nn.functional as F
from torchvision import models

class FFClassifier(nn.Module):

    def __init__(self, in_features, hidden_features, 
                       out_features, drop_prob=0.1):
        super().__init__()

        self.fc1 = nn.Linear(in_features, hidden_features)
        self.fc2 = nn.Linear(hidden_features, out_features)
        self.drop = nn.Dropout(p=drop_prob)

    def forward(self, x):
        x = self.drop(F.relu(self.fc1(x)))
        x = self.fc2(x)
        x = F.log_softmax(x, dim=1)
        return x


def load_checkpoint(checkpoint_path):
    checkpoint = torch.load(checkpoint_path)

    model = models.vgg16(pretrained=False)
    for param in model.parameters():
        param.requires_grad = False

    # Put the classifier on the pretrained network
    model.classifier = FFClassifier(25088, checkpoint['hidden'], 102)

    model.load_state_dict(checkpoint['state_dict'])

    return model

model = load_checkpoint('/home/workspace/classifier.pt')

Your exact code here will depend on how you defined your network in the project. Make sure you use the absolute path to your checkpoint which should have been uploaded to the /home/workspace directory.

Run the cell, then after loading the data, press "Test Code" below. This can take a few minutes or more depending on the size of your network. Your model needs to reach at least 20% accuracy on the test set to be recorded.


In [1]:
import torch
from torch import nn
from torch import optim
import torch.nn.functional as F
from torch.autograd import Variable
from torchvision import datasets, transforms, models

# TODO: Build and train your network
def build_model(class_to_idx):
    model = models.resnet18(pretrained=True).cpu()

    # Freezing the features
    for param in model.parameters():
        param.requires_grad_(False)
    from collections import OrderedDict

    model.fc = nn.Sequential(OrderedDict([
            ('fc1', nn.Linear(512, 256)),
            ('relu', nn.ReLU()),
            ('fc2', nn.Linear(256, 102)),
            ('output', nn.LogSoftmax(dim=1))

           ]))

    # Setting trainable parameters
    for trainable_params in model.fc.parameters():
        trainable_params.requires_grad_(True)
    model.class_to_idx = class_to_idx
    print('Model created!')
    return model

full_model_path = 'lab_best_model_full_model.pth'
full_model_dict_loaded = torch.load(full_model_path, map_location=lambda storage, loc: storage)
lr_loaded = full_model_dict_loaded['lr']
class_to_idx_loaded = full_model_dict_loaded['class_to_idx']
model = build_model(class_to_idx=class_to_idx_loaded)


Model created!

In [2]:
model.load_state_dict(full_model_dict_loaded['state_dict'])

In [3]:
# Load your model to this variable
model = model 
   
# If you used something other than 224x224 cropped images, set the correct size here
image_size = 224
# Values you used for normalizing the images. Default here are for 
# pretrained models from torchvision.
norm_mean = [0.485, 0.456, 0.406]
norm_std = [0.229, 0.224, 0.225]